from django.shortcuts import render,HttpResponse
from rest_framework.exceptions import APIException
from rest_framework.views import APIView
from utils.log import get_logger
from utils.response import APIResponse


logger = get_logger()
# def index(request):
#
#     logger.info('我是日志')
#     return HttpResponse('OK')


# class indexView(APIView):
#     def get(self,request):
#         print('请求来了')
#         # raise APIException('不让你过')
#         return APIResponse(data=[{'name':'ycc','age':'19'},{'name':'ll','age':20}])

from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from .serializer import UserModelSerializer,MobileLoginSerializer
from .models import User
class LoginView(ViewSet):
    @action(methods=['POST'],detail=False)
    def login(self,request,*args,**kwargs):
        ser = UserModelSerializer(data=request.data)
        if ser.is_valid():
            # 登录成功
            username = ser.context['username']
            token = ser.context['token']
            user = ser.context['user']
            return APIResponse(username=username,token=token,id=user.id)
            # return APIResponse(username=username,token=token,id=ser.instance.id)
        else:
            # 登录失败
            return APIResponse(code=101,msg=ser.errors)

    def mobile_login(self,request):
        # 逻辑写在序列化类中
        ser = MobileLoginSerializer(data=request.data)
        ser.is_valid(raise_exception=True)  # 执行序列化类字段自己的校验规则，局部钩子，全局钩子
        token = ser.context.get('token')
        username = ser.context.get('username')
        return APIResponse(msg='登录成功',username=username,token=token)

from lib import tx_sms
from .throttle import SMSThrottle
from django.conf import settings
import re
# 导入django缓存模块,由于没有配置，默认在内存，可以改到redis中缓存
from django.core.cache import cache
class MobileView(ViewSet):
    @action(methods=['GET'],detail=False,url_path='mobile')
    # url_path:给check_mobile方法起了个别名：mobile
    def check_mobile(self,request):
        mobile = request.GET.get('mobile')
        try:
            User.objects.get(mobile=mobile)
            return APIResponse(is_exist=True)
        except Exception:
            raise APIException('手机号不存在')

    @action(methods=['GET'], detail=False, url_path='sms', throttle_classes=[SMSThrottle])
    def send_sms(self, request):
        mobile = request.query_params.get('mobile')
        if mobile and re.match('^1[3-9][0-9]{9}$', mobile):
            # 发送短信
            # 获取验证码，记录验证码（放到缓存中，默认还是缓存到内存）
            code = tx_sms.get_code()
            cache.set(settings.CACHE_SMS % mobile, code)
            print(mobile)
            print(code)
            # 调用发送短信函数
            res = tx_sms.send_sms(mobile, code)
            print(res)
            if res:
                return APIResponse(msg='短信发送成功')
            else:
                raise APIException('短信发送失败')
        else:
            raise APIException('手机号不合法')


# 保存，序列化类
# 自动生成路由，跟数据库打交道,create方法，
from rest_framework.viewsets import ViewSetMixin, GenericViewSet
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from .models import User
from .serializer import RegisterUserSerializer

class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = User.objects.all()
    serializer_class = RegisterUserSerializer
    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)

        return APIResponse(msg='注册成功')





